import axios from 'axios'
import x2jsOb from 'x2js'
// import gConfig from '@/utils/GlobalConfig'

export default {
  x2js: null,
  initx2js() {//读取xml文件，转换为json
    if (this.x2js == null) {
      this.x2js = new x2jsOb()//这个x2js必须new一个。就放到初始方法中吧
    }
  },
  //zpf 2022年7月14日 添加xyz服务
  addXYZService(map, option, feature) {
    //2022年7月21日 LQ 添加type和id信息
    let xyzLayer = new ol.layer.Tile({
      opacity: 1,
      name: option.name,
      id: option.id,
      type: option.type,
      source: new ol.source.XYZ({
        url: option.url
      })
    })
    map.addLayer(xyzLayer)
    if (option.zmin) {
      xyzLayer.setMinZoom(option.zmin)
    }
    if (option.zmax) {
      xyzLayer.setMaxZoom(option.zmax)
    }
    xyzLayer.setZIndex(option.zIndex)
    //feature转投影

    if (feature) {
      ol.supermap.Util.setMask(xyzLayer, feature)
    }
  },
  //zpf 2022年5月30日 添加geoserver的wmts服务
  addGeoserverWMTSService(map, option, feature) {
    let layerWMTS
    let parser = new ol.format.WMTSCapabilities()
    let wmtsUrl = option.url
    let layerTitle = getUrlParam1(wmtsUrl, 'layer')
    fetch(wmtsUrl).then(response => response.text()).then(text => {
      let result = parser.read(text)
      let options = ol.source.WMTS.optionsFromCapabilities(result, {
        layer: layerTitle
      })
      let extentWidth = ol.extent.getWidth(options.projection.getExtent())
      for (let i in options.tileGrid.resolutions_) {
        let tileSize = options.tileGrid.tileSizes_[i]
        options.tileGrid.resolutions_[i] = extentWidth / tileSize / Math.pow(2, parseInt(i) + 1)
      }
      layerWMTS = new ol.layer.Tile({
        opacity: 1,
        name: option.name,
        id: option.id,
        type: option.type,
        source: new ol.source.WMTS(options)
      })
      map.addLayer(layerWMTS)
      if (option.zmin) {
        layerWMTS.setMinZoom(option.zmin)
      }
      if (option.zmax) {
        layerWMTS.setMaxZoom(option.zmax)
      }
      layerWMTS.setZIndex(option.zIndex)
      //feature转投影

      if (feature) {
        ol.supermap.Util.setMask(layerWMTS, feature)
      }
    })
  },
  //加载矢量瓦片
  addRESTJSRLayer(map, option, feature) {
    let format = new ol.format.MVT({
      featureClass: ol.Feature
    })
    let style = new ol.supermap.MapboxStyles({
      style: option.url,
      // source: 'China_4326',
      map: map
    })
    let vectorLayer = null
    style.on('styleloaded', function() {
      vectorLayer = new ol.layer.VectorTile({
        declutter: true,
        opacity: 1,
        name: option.name,
        id: option.id,
        type: option.type,
        source: new ol.source.VectorTileSuperMapRest({
          style: option.url,
          projection: option.sys,
          crossOrigin: 'anonymous',
          //   projection: 'EPSG:4490',
          // source: 'China_4326',
          format: format
        }),
        style: style.getStyleFunction()
      })
      map.addLayer(vectorLayer)
      vectorLayer.setZIndex(option.zIndex)
      // GetLayerFunc(layer);
    })

  },
  //新增了visible属性
  addWMTS4490Layer: function(map, option, feature) {
    let layerWMTS
    axios.get(option.url, {
      // params: param
    }).then((res) => {
      let sysCode = parseInt(option.sys.replace('EPSG:', ''))
      let projection = null
      let topResolution = 0
      let resolutions = []
      let visible = true
      let matrixIds = []
      if (sysCode == 4490) {
        topResolution = (360 / 512)
      } else if ((sysCode >= 2327 && sysCode <= 2390) || (sysCode >= 4490 && sysCode <= 4554)) {
        let leftbottom = [90, 45]
        let projleftBottom = ol.proj.transform(leftbottom, 'EPSG:4490', option.sys)
        //let projleftBottom=[42526598.816700004,5432437.912600001];
        topResolution = (projleftBottom[0] / 512)
      } else {
        projection = ol.proj.get(option.sys)
        let projectionExtent = projection.getExtent()
        //2021年12月23日 LQ 发现用256是错的，要用512
        //  topResolution = (ol.extent.getWidth(projectionExtent) / 256);
        topResolution = (ol.extent.getWidth(projectionExtent) / 512)
      }
      for (let zoom = 0; zoom < 22; zoom++) {
        resolutions.push(topResolution / Math.pow(2, zoom))
        matrixIds[zoom] = zoom
      }
      let bounds = []
      let matrixSet = ''
      //如果别的地方没注册的话，就执行一遍initx2js
      this.initx2js();
      let json = this.x2js.xml2js(res.data)
      let layer = json.Capabilities.Contents.Layer
      let layerName = layer.Title.__text
      for (let i = 0; i < layer.BoundingBox.length; i++) {
        let bb = layer.BoundingBox[i]
        if (bb._crs.indexOf(sysCode) > -1) {
          let lowerStr = bb.LowerCorner.__text
          let lc = lowerStr.trim().split(/\s+/)
          let upperStr = bb.UpperCorner.__text
          let uc = upperStr.trim().split(/\s+/)
          bounds.push(parseFloat(lc[0]))
          bounds.push(parseFloat(lc[1]))
          bounds.push(parseFloat(uc[0]))
          bounds.push(parseFloat(uc[1]))
        }
      }
      matrixSet = layer.TileMatrixSetLink[0].TileMatrixSet
      //2022年7月18日 LQ 增加了visible属性，可控制map加载图层但是不显示。
      if (option.visible === false) {
        visible = false
      }
      layerWMTS = new ol.layer.Tile({
        opacity: 1,
        visible: visible,
        name: option.name,
        id: option.id,
        type: option.type,
        source: new ol.source.WMTS({
          url: option.url,
          layer: layerName,
          matrixSet: matrixSet,
          format: 'image/png',
          projection: option.sys, //'EPSG:4490',
          tileGrid: new ol.tilegrid.WMTS({
            origin: [bounds[0], bounds[3]],
            extent: [bounds[0], bounds[1], bounds[2], bounds[3]],
            resolutions: resolutions,
            matrixIds: matrixIds
          }),
          crossOrigin: 'anonymous',
          style: 'default'
        })
      })
      if (feature) {
        ol.supermap.Util.setMask(layerWMTS, feature)
      }

      if (option.zmin) {
        layerWMTS.setMinZoom(option.zmin)
      }
      if (option.zmax) {
        layerWMTS.setMaxZoom(option.zmax)
      }
      layerWMTS.setZIndex(option.zIndex)
      //feature转投影
      map.addLayer(layerWMTS)

    }).catch((error) => {
      // catch 指请求出错的处理
      //  console.log('AddWMTS4490Layer', error);
    })
  },
  addREST4490Layer: function(map, option, feature) {
    let that = this
    let Layer = new ol.layer.Tile({
      source: new ol.source.TileSuperMapRest({
        url: option.url,
        crossOrigin: 'anonymous',
        wrapX: true
      }),
      projection: option.sys, //'EPSG:4490',
      name: option.name,
      id: option.id,
      type: option.type//类型 数据1 底图0
    })
    Layer.setZIndex(option.zIndex)
    map.addLayer(Layer)
    if (option.zmin) {
      Layer.setMinZoom(option.zmin)
    }
    if (option.zmax) {
      Layer.setMaxZoom(option.zmax)
    }
    if (feature) {
      ol.supermap.Util.setMask(Layer, feature)
    }
  },
  addTDTWMTSService: function(map, option, feature) {
    let that = this
    let url = option.url //在线
    let urlsplits = url.split('/')
    if (!urlsplits[3].indexOf('_')) {
      return
    }
    let lyrs = urlsplits[3].split('_')
    let lyr = lyrs[0]
    let matrixSet = lyrs[1]
    let visible = true
    let projection = ol.proj.get(option.sys)
    let projectionExtent = projection.getExtent()
    let maxResolution = (ol.extent.getWidth(projectionExtent) / 256)
    let resolutions = new Array(20)
    let matrixIds = new Array(16)
    let z
    for (z = 0; z < 16; ++z) {
      resolutions[z] = maxResolution / Math.pow(2, z)
      matrixIds[z] = z
    }
    let tileOrigin = ol.extent.getTopLeft(projectionExtent)
    //2022年7月18日 LQ 增加了visible属性
    if (option.visible === false) {
      visible = false
    }
    let layerWMTS = new ol.layer.Tile({
      opacity: 1,
      name: option.name,
      id: option.id,
      type: 0,
      visible: visible,
      source: new ol.source.WMTS({
        url: url,
        layer: lyr,
        matrixSet: matrixSet,
        format: 'tiles',
        projection: projection,
        tileGrid: new ol.tilegrid.WMTS({
          origin: tileOrigin,
          resolutions: resolutions,
          matrixIds: matrixIds
        }),
        style: 'default',
        crossOrigin: 'anonymous',
        wrapX: true
      })
    })
    map.addLayer(layerWMTS)
    if (option.zmin) {
      layerWMTS.setMinZoom(option.zmin)
    }
    if (option.zmax) {
      layerWMTS.setMaxZoom(option.zmax)
    }
    layerWMTS.setZIndex(option.zIndex)
    //feature转投影

    if (feature) {
      ol.supermap.Util.setMask(layerWMTS, feature)
    }
  },
  addPlacenameMarker: function(msg, overSource) {
    let iconurl = msg[0]
    let position = msg[1]
    let index = msg[2]
    var that = this
    //设置marker样式
    var iconstyle = new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 24],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        //注意啊,这个地方的iconurl用的是静态资源public/images里的。
        //若之前使用assets的话，话把<4kb的图片改为base64格式的，这样就找不到图片了
        // src: require(`@/assets/${iconurl}`),
        //2022年8月31日 LQ 下面这个正确的url谁给删除了？？？
        src: iconurl
      })
    })
    var poifeature = new ol.Feature({
      index: index,
      geometry: new ol.geom.Point(position)
    })
    poifeature.setStyle(iconstyle)
    overSource.addFeature(poifeature)
  },
  addServiceToMap: function(map, option, feature) {
    let that = this
    switch (option.servicetype) {
      case 1:
        that.addREST4490Layer(map, option, feature)
        break
      case 2://restjsr矢量瓦片服务类型
        that.addRESTJSRLayer(map, option, feature)
        break
      case 3:
      case 4:
      case 5:
      case 6:
        that.addWMTS4490Layer(map, option, feature)
        break
      case 7:
        that.addTDTWMTSService(map, option, feature)
        break
      case 8:
        that.addGeoserverWMTSService(map, option, feature)
        break
      case 9:
        that.addXYZService(map, option, feature)
        break
    }
  },
  addWKT2Layer(map, layerObj, geowkt, id, color, isZoomTo, prjcode) {
    var that = this
    var feature = that.createFeature(map, geowkt, id, color, prjcode)
    layerObj.getSource().addFeature(feature)
    if (isZoomTo) {
      var extent = feature.getGeometry().getExtent()
      var tol = that.tol
      var extentObj = {
        center: { x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2 },
        width: Math.abs(extent[2] - extent[0]),
        height: Math.abs(extent[3] - extent[1])
      }
      if (extentObj.width < tol && extentObj.height < tol) {
        extent = [extentObj.center.x - tol / 2, extentObj.center.y - tol / 2, extentObj.center.x + tol / 2, extentObj.center.y + tol / 2]
      }
      map.getView().fit(extent, { size: map.getSize(), padding: [100, 100, 100, 100] })
    }
  },
  clearLayerById: function(map, layerId) {
    let that = this
    let layer = that.getLayerById(map, layerId)
    if (layer) {
      //layer.getSource().clear();
      //layer.setVisible(false);
      map.removeLayer(layer)
    }
  },
  setNoVisibleLayerById: function(map, layerId) {
    let that = this
    let layer = that.getLayerById(map, layerId)
    if (layer) {
      layer.setVisible(false)
    }
  },
  clearLayerByName(map, layerName) {
    var that = this
    var layer = that.getLayerByName(map, layerName)
    if (layer) {
      layer.getSource().clear()
    }
  },
  clearOverSource: function(map, overSource) {
    // mapCore.overSource.clear();
    overSource.clear()
    this.removeInteractions(map)
  },
  clearOverSourceByKeyValue: function(map, overSource, key, value) {
    overSource.getFeatures().forEach((feature, index) => {
      let cValue = feature.get(key)
      if (cValue == value) {
        overSource.removeFeature(feature)
      }
    })
    this.removeInteractions(map)
  },
  clearSelectedFeature: function(map, oveSource) {
    var that = this
    that.clearOverSource(map, oveSource)
    //2022年4月14日 LQ selectFeature没用上，注释掉试一下
    // if (mapCore.selectFeature != null) {
    //     mapCore.selectFeature.getFeatures().clear();
    // }
    that.removeOverlayLikeName(map, 'measureResult')
    //  that.removeAllDrawInteractions(map);
    // that.removeAllSnapInteractions(map);
  },
  closeLayerExceptId: function(map, layerId1, layerId2) {
    var that = this
    //根据名称获取图层
    var result = null
    map.getLayers().forEach(function(layer, i) {
      if (layer.get('id') != layerId1 && layer.get('id') != layerId2) {
        layer.setVisible(false)
      } else {
        layer.setVisible(true)
      }
    })
    return result
  },
  /**
   * 创建要素
   * @param {type} geowkt
   * @param {type} id
   * @param {type} color
   * @return {Feature}
   */
  createFeature(map, geowkt, id, color, prjcode) {
    let that = this
    if (!color) {
      color = { r: 255, g: 0, b: 0, a: 0.5 }
    }
    if (color.a || color.a == 0) {

    } else {
      color.a = 0.5
    }
    let format = new ol.format.WKT()
    let feature = format.readFeature(geowkt, {
      dataProjection: prjcode,
      featureProjection: map.getView().getProjection().getCode()
    })
    let geometryType = feature.getGeometry().getType()
    let offsetY = 0
    if (geometryType.toUpperCase().indexOf('POINT') >= 0) {
      offsetY = 15
    }
    feature.set('featureid', id)
    let showtext = id ? id.toString() : ''
    feature.setStyle(new ol.style.Style({
      image: new ol.style.Circle({
        radius: 5,
        stroke: new ol.style.Stroke({
          color: 'rgba(255,255,0,1)',
          width: 1
        }),
        fill: new ol.style.Fill({
          color: 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',0.8)'
        })
      }),
      stroke: new ol.style.Stroke({
        color: 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',1)',
        width: 3
      }),
      fill: new ol.style.Fill({
        color: 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')'
      })
      // text: new ol.style.Text({
      //   fill: new ol.style.Fill({
      //     color: 'rgba(0,0,0,1)'
      //   }),
      //   stroke: new ol.style.Stroke({
      //     color: 'rgba(255,255,255,1)',
      //     width: 3
      //   }),
      //   offsetX: 0,
      //   offsetY: offsetY,
      //   text: showtext
      // })
    }))
    return feature
  },

  /**
   * 创建或重新初始化图层.指定样式 图层名字 why20211101
   * @param {type} layerName
   * @return {ol.layer.Vector}
   */
  createLayer: function(map, features, layerName, id, type, fillcolor, strokecolor) {
    var that = this
    var layer = that.getLayerByName(map, layerName)
    if (layer) {
      layer.getSource().clear()
    } else {
      var overSource = new ol.source.Vector({
        features: features,
        crossOrigin: 'anonymous',
        wrapX: false
      })
      layer = new ol.layer.Vector({
        name: layerName,
        id: id,
        type: type,
        source: overSource,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: fillcolor
          }),
          stroke: new ol.style.Stroke({
            //  color: '#ffcc33', //'#38c1ea',
            color: strokecolor,
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: strokecolor
            })
          })
        })
      })
      map.addLayer(layer)
      layer.setZIndex(9998)
    }
    return layer
  },

  /**
   * 创建或重新初始化行政区注记图层.指定样式 图层名字 lq 2022年8月27日
   * @param {type} layerName
   * @return {ol.layer.Vector}
   */
  createLayerEasy: function(map, layerName, id, type, zindex) {
    var that = this
    var layer = that.getLayerByName(map, layerName)
    if (layer) {
      // layer.getSource().clear()
    } else {
      var overSource = new ol.source.Vector({
        // features: features,
        crossOrigin: 'anonymous',
        wrapX: false
      })
      layer = new ol.layer.Vector({
        name: layerName,
        id: id,
        type: type,
        source: overSource,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(252,252,252,0)'
          }),
          stroke: new ol.style.Stroke({
            //  color: '#ffcc33', //'#38c1ea',
            color: 'rgba(252,252,252,0)',
            width: 1
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: 'rgba(252,252,252,0)'
            })
          }),
          text: new ol.style.Text({
            textAlign: 'center',     //对齐方式
            textBaseline: 'middle',    //文本基线
            font: '14px sans-serif', // 设置字体
            maxAngle: 30,
            offsetx: 10, // 设置文字偏移量
            offsetY: 10,
            text: '', // 文字描述
            fill: new ol.style.Fill({
              // 字体颜色
              color: '#1fbfaf'
            }),
            stroke: new ol.style.Stroke({
              // 文字描边
              color: '#fff',
              width: 5
            })
          })
        })
      })
      map.addLayer(layer)
      layer.setZIndex(zindex)
    }
    return layer
  },

  //固定死样式的一种方法
  createLayerEasy2: function(map, layerName, id, type, zindex, textConfig) {
    var that = this
    var layer = that.getLayerByName(map, layerName)
    if (layer) {
      // layer.getSource().clear()
    } else {
      var overSource = new ol.source.Vector({
        // features: features,
        crossOrigin: 'anonymous',
        wrapX: false
      })
      layer = new ol.layer.Vector({
        name: layerName,
        id: id,
        type: type,
        source: overSource,
        style: function(feature) {
          return new ol.style.Style({
            text: new ol.style.Text({
              textAlign: 'center',     //对齐方式
              textBaseline: 'middle',    //文本基线
              font: textConfig.font, // 设置字体
              //  maxAngle: 30,
              // offsetx: 10, // 设置文字偏移量
              // offsetY: 10,
              text: feature.get('XZQMC'.toUpperCase()), // 文字描述
              fill: textConfig.fill,
              stroke: textConfig.stroke
            })
          })
        }
      })
      map.addLayer(layer)
      layer.setZIndex(zindex)
    }
    return layer
  },
  /**
   * 创建或重新初始化行政区注记图层.指定样式 图层名字 lq 2022年8月27日
   * @param {type} layerName
   * @return {ol.layer.Vector}
   */

  createClusterLayer: function(map, layerName, id, type, zindex, clusterSource) {
    var that = this
    var layer = that.getLayerByName(map, layerName)
    if (layer) {
      // layer.getSource().clear()
    } else {
      // var overSource = new ol.source.Vector({
      //     // features: features,
      //     crossOrigin: 'anonymous',
      //     wrapX: false
      // })
      layer = new ol.layer.Vector({
        name: layerName,
        id: id,
        type: type,
        source: clusterSource,
        style: function(feature) {
          let features = feature.get('features')
          let size = features.length
          return new ol.style.Style({
            // fill: new ol.style.Fill({
            //     color: 'rgba(252,252,252,0)'
            // }),
            // stroke: new ol.style.Stroke({
            //     //  color: '#ffcc33', //'#38c1ea',
            //     color: 'rgba(252,252,252,0)',
            //     width: 1
            // }),
            // image: new ol.style.Circle({
            //     radius: 7,
            //     fill: new ol.style.Fill({
            //         color: 'rgba(252,252,252,0)'
            //     })
            // }),
            text: new ol.style.Text({
              textAlign: 'center',     //对齐方式
              textBaseline: 'middle',    //文本基线
              font: '14px sans-serif', // 设置字体
              //  maxAngle: 30,
              // offsetx: 10, // 设置文字偏移量
              // offsetY: 10,
              text: size.toString(), // 文字描述
              fill: new ol.style.Fill({
                // 字体颜色
                color: '#1fbfaf'
              }),
              stroke: new ol.style.Stroke({
                // 文字描边
                color: '#fff',
                width: 3
              })
            })
          })
        }
      })
      map.addLayer(layer)
      layer.setZIndex(zindex)
    }
    return layer
  },

  /**
   * 根据ID获取图层
   * @param {type} layerName
   * @return {unresolved}
   */
  getLayerById: function(map, layerId) {
    let that = this
    //根据名称获取图层
    let result = null
    map.getLayers().forEach(function(layer, i) {
      if (layer.get('id') == layerId) {
        result = layer
      }
    })
    return result
  },

  //根据名称获取图层 2022年2月28日 LQ 已改完
  getLayerByName: function(map, layerName) {
    var that = this
    var result = null
    map.getLayers().forEach(function(layer, i) {
      if (layer.get('name') == layerName) {
        result = layer
      }
    })
    return result
  },
  getLayerByType: function(map, layerType) {
    let that = this
    //根据名称获取图层
    var result = []
    map.getLayers().forEach(function(layer, i) {
      if (layer.get('type') == layerType) {
        result.push(layer)
      }
    })
    return result
  },
  getOpenLayers: function(mapCore) {
    var that = this
    mapCore.map.getLayers().forEach(function(layer, i) {
      if (layer.getVisible()) {
        mapCore.openLayerIds.push(layer.get('id'))
      }
    })
  },
  //加载底图
  loadMapServices: function(map, layers, type) {
    let that = this
    //地图中其他底图关闭
    let zIndex = 90
    map.getLayers().forEach(function(layer, i) {
      if (layer.get('type') == type) {
        layer.setVisible(false)
        zIndex--
      }
    })
    for (let i in layers) {
      let layerParam = layers[i]
      let layer = that.getLayerById(map, layerParam.f_id)
      if (layer) {//图层已存在
        if (!layer.getVisible()) {
          layer.setVisible(true)
        }
      } else {
        let Layer
        let feature = null
        let sys = 'EPSG:4490'
        if (layerParam.f_sys != '') {
          sys = 'EPSG:' + layerParam.f_sys
        }
        zIndex--
        let zIndexThis = zIndex
        // if (layerParam.f_islabel == 1) {
        //   zIndexThis = 9999;
        // }
        let option = {
          url: layerParam.f_url,
          name: layerParam.f_name,
          id: layerParam.f_id,
          sys: sys,
          zIndex: layerParam.f_islabel == 1 ? 9999 : zIndexThis,
          type: type,
          zmin: layerParam.f_zmin,
          zmax: layerParam.f_zmax
        }
        if (layerParam.f_servicetype == 1) {// 加载 rest
          Layer = that.addREST4490Layer(map, option, null)
        } else if (layerParam.f_servicetype == 4) {//加载 wmts
          Layer = that.addWMTS4490Layer(map, option, null)
        } else if (layerParam.f_servicetype == 7) {//加载 wmts
          Layer = that.addTDTWMTSService(map, option, null)
        } else if (layerParam.f_servicetype == 8) {//加载 geoserverwmts
          Layer = that.addGeoserverWMTSService(map, option, null)
        } else if (layerParam.f_servicetype == 9) {//加载 xyzServer
          Layer = that.addXYZService(map, option, null)
        }
      }
    }
  },
  //打开所有图层
  openLayers(map) {
    var that = this
    //根据名称获取图层
    var result = null
    map.getLayers().forEach(function(layer, i) {
      if (!layer.getVisible()) {
        layer.setVisible(true)
      }
    })
    return result
  },
  /**
   * 根据名称清除图层
   * @param {type} layerName
   * @return {undefined}
   */
  removeAllDrawInteractions: function(map) {
    var that = this
    map.getInteractions().forEach(function(interaction) {
      if (interaction instanceof ol.interaction.Draw) {
        map.removeInteraction(interaction)
      }
    })
  },
  removeAllSnapInteractions: function(map) {
    var that = this
    map.getInteractions().forEach(function(interaction) {
      if (interaction instanceof ol.interaction.Snap) {
        map.removeInteraction(interaction)
      }
    })
  },
  removeInteractions: function(map) {
    var that = this
    //移除事件响应
    that.removeAllDrawInteractions(map)
    that.removeAllSnapInteractions(map)
  },
  //根据名称移除Overlay
  removeOverlayLikeName: function(map, overlayName) {
    var that = this
    try {
      //ClearSelectedFeature();
      var overlays = []
      map.getOverlays().forEach(function(overlay, i) {
        try {
          var name = overlay.id
          if (name.indexOf(overlayName) >= 0) {
            overlays.push(overlay)
          }
        } catch (e) {
        }
      })
      for (var i in overlays) {
        map.removeOverlay(overlays[i])
      }
      return true
    } catch (err) {
      return false
    }
  },
  /**
   * 缩放至指定图层          * @param {type} layer
   * @return {undefined}          */
  zoomToLayer: function(map, layer) {
    var that = this
    if (layer) {
      if (layer.getSource().getFeatures().length == 0) {
        return
      }
      var extent = layer.getSource().getExtent()
      map.getView().fit(extent, { size: map.getSize(), padding: [100, 100, 100, 100] })
    }
  },
  zoomToExtent: function(map, geomOrExtent) {
    let that = this
    if (geomOrExtent) {
      if (geomOrExtent[0].toString() == 'Infinity') {
        return
      }
      if (geomOrExtent[0] == geomOrExtent[2] && geomOrExtent[1] == geomOrExtent[3]) {
        map.getView().fit(geomOrExtent, { maxZoom: 12 })
      } else {
        map.getView().fit(geomOrExtent, {
          size: map.getSize(), //当前图形要缩放到的窗口大小，一般设置为当前地图窗口大小；也可以自己指定[100,100]
          padding: [100, 100, 100, 100], //view缩放过去的padding属性，顺序为top right bottom left
          constrainResolution: false, //是否约束resolution
          nearest: false, //合constrainResolution使用，意思是缩放到的级别是否需要设置为最近的resolution，通过这俩属性来控制，true则自动缩放到最近的res；
          minResolution: 0, //最小res maxZoom:0,//最大缩放级别，minResolution如果设置了，这个则会被忽略 duration:1000,//缩放持续时间，默认不需要设置
          easing: function() {
          }, //结合duration控制缩放时动画，动画期间使用的缓动功能，将为每个帧调用该函数，其中一个数字表示动画持续时间的一小部分。
          callback: function() {
          } //缩放完成事件 }); //属性一般只需要设置size即可。
        })
      }
    }
  }
}
